package com.tencent.wxcloudrun.service.business.zuke;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tencent.wxcloudrun.pojo.bo.ContractGenerateTask;
import com.tencent.wxcloudrun.pojo.bo.ContractTaskStatusEnum;
import com.tencent.wxcloudrun.pojo.bo.NoticeConstant;
import com.tencent.wxcloudrun.pojo.bo.SonStateZuFangEnum;
import com.tencent.wxcloudrun.pojo.po.XApplyMiddle;
import com.tencent.wxcloudrun.pojo.po.XHelpmateInfo;
import com.tencent.wxcloudrun.pojo.po.XPersonInfo;
import com.tencent.wxcloudrun.service.XApplyMiddleService;
import com.tencent.wxcloudrun.service.XHelpmateInfoService;
import com.tencent.wxcloudrun.service.XPersonInfoService;
import com.tencent.wxcloudrun.service.business.ContractAsyncService;
import com.tencent.wxcloudrun.service.business.NoticeService;
import com.tencent.wxcloudrun.util.WinXinUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

@Service
@Slf4j
public class ZuKeTodoService {

    @Resource
    private XApplyMiddleService xApplyMiddleService;

    @Resource
    private XPersonInfoService xPersonInfoService;

    @Resource
    private XHelpmateInfoService xHelpmateInfoService;

    @Resource
    private NoticeService noticeService;

    @Resource
    private WinXinUtils winXinUtils;

    @Resource
    private ContractAsyncService contractAsyncService;

    @Transactional(rollbackFor = Exception.class)
    public String rejectOrAgree(String id, String state, String reason) throws IOException {
        // 租客同意节点，不再生成合同，合同在房东确认收款时（节点四）才正式生成
        XApplyMiddle xApplyMiddle = new XApplyMiddle();
        xApplyMiddle.setSonThreeState("1".equals(state) ? SonStateZuFangEnum.SUCCESS.getValue() : SonStateZuFangEnum.FAILED.getValue());
        xApplyMiddle.setSonThreeReason(reason);
        LambdaQueryWrapper<XApplyMiddle> xApplyMiddleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        xApplyMiddleLambdaQueryWrapper.eq(XApplyMiddle::getSonThreeId, id);
        xApplyMiddleService.update(xApplyMiddle, xApplyMiddleLambdaQueryWrapper);
        // 检查这个房子是否又助理在管理
        XApplyMiddle applyMiddle = xApplyMiddleService.getOne(xApplyMiddleLambdaQueryWrapper);
        // 如果是拒绝，要把节点二改成process状态
        if ("2".equals(state)) {
            LambdaQueryWrapper<XApplyMiddle> xApplyMiddleLambdaQueryWrapper1 = new LambdaQueryWrapper<>();
            xApplyMiddleLambdaQueryWrapper1.eq(XApplyMiddle::getSonTwoId, applyMiddle.getSonTwoId());
            XApplyMiddle xApplyMiddle1 = new XApplyMiddle();
            xApplyMiddle1.setSonTwoState(SonStateZuFangEnum.WAIT.getValue());
            xApplyMiddleService.update(xApplyMiddle1, xApplyMiddleLambdaQueryWrapper1);
        }
        LambdaQueryWrapper<XHelpmateInfo> xHelpmateInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        xHelpmateInfoLambdaQueryWrapper.eq(XHelpmateInfo::getLandlordId, applyMiddle.getLandId());
        xHelpmateInfoLambdaQueryWrapper.like(XHelpmateInfo::getHouseList, applyMiddle.getHouseId());
        List<XHelpmateInfo> helpList = xHelpmateInfoService.list(xHelpmateInfoLambdaQueryWrapper);
        // 找出租客的个人信息
        LambdaQueryWrapper<XPersonInfo> xPersonInfoTenant = new LambdaQueryWrapper<>();
        xPersonInfoTenant.eq(XPersonInfo::getPersonId, applyMiddle.getTenantId());
        xPersonInfoTenant.eq(XPersonInfo::getPersonType, "tenant");
        XPersonInfo tenantInfo = xPersonInfoService.getOne(xPersonInfoTenant);
        // 找出房东的个人信息
        LambdaQueryWrapper<XPersonInfo> xPersonInfoLand = new LambdaQueryWrapper<>();
        xPersonInfoLand.eq(XPersonInfo::getPersonId, applyMiddle.getLandId());
        xPersonInfoLand.eq(XPersonInfo::getPersonType, "landlord");
        XPersonInfo landInfo = xPersonInfoService.getOne(xPersonInfoTenant);
        int helpFlag = 0; // 0表示没有助理，1表示有助理
        if (CollUtil.isNotEmpty(helpList)) { // 表明这间房子有助理在管理，甚至可能有多个，给他们发送通知
            for (XHelpmateInfo xHelpmateInfo : helpList) {
                ++helpFlag;
                noticeService.createNoticeByOpenid(xHelpmateInfo.getHelpmateId(), "helpmate",
                        NoticeConstant.APPLY_HOUSE_THREE_HELP_TITLE,
                        String.format(NoticeConstant.APPLY_HOUSE_THREE_HELP_CONTENT, "1".equals(state) ? "同意" : "拒绝",
                                "1".equals(state) ? "无，请尽快联系租客完成第四步的签署确认。" : reason, tenantInfo.getCardName(), tenantInfo.getPhone()));
            }
        }
        // 给这个房子的房东发送一个通知
        noticeService.createNoticeByOpenid(applyMiddle.getLandId(), "land",
                NoticeConstant.APPLY_HOUSE_THREE_LAND_TITLE,
                String.format(NoticeConstant.APPLY_HOUSE_THREE_LAND_CONTENT, "1".equals(state) ? "同意" : "拒绝",
                        "1".equals(state) ? "无，请尽快联系租客完成第四步的签署确认。" : reason, tenantInfo.getCardName(),
                        (helpFlag == 0 ? tenantInfo.getPhone() : tenantInfo.getPhone() + "，该信息已同步至助理")));
        // 给租客生成一个通知
        noticeService.createNoticeByOpenid(tenantInfo.getPersonId(), "tenant",
                NoticeConstant.APPLY_HOUSE_THREE_TENANT_TITLE,
                String.format(NoticeConstant.APPLY_HOUSE_THREE_TENANT_CONTENT, "1".equals(state) ? "同意" : "拒绝",
                        "1".equals(state) ? "无" : reason + "，可联系房东进行协商处理。",
                        (helpFlag == 0 ? landInfo.getCardName() : helpList.get(0).getAlias()),
                        (helpFlag == 0 ? landInfo.getPhone() : helpList.get(0).getHelpPhone())));
        return "success";
    }

    public String preview(String threeId) {
        // 获取申请信息，查找可能的任务ID
        LambdaQueryWrapper<XApplyMiddle> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(XApplyMiddle::getSonThreeId, threeId);
        XApplyMiddle applyMiddle = xApplyMiddleService.getOne(wrapper);

        if (applyMiddle == null || StrUtil.isBlank(applyMiddle.getContractId())) {
            return null;
        }
        return winXinUtils.batchdownloadfile(applyMiddle.getFileId());
    }

    /**
     * 获取任务状态信息（用于前端显示）
     */
    public ContractGenerateTask getTaskStatus(String sonThreeId) {
        try {
            // 获取申请信息，查找可能的任务ID
            LambdaQueryWrapper<XApplyMiddle> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(XApplyMiddle::getSonThreeId, sonThreeId);
            XApplyMiddle applyMiddle = xApplyMiddleService.getOne(wrapper);

            if (applyMiddle == null || StrUtil.isBlank(applyMiddle.getContractId())) {
                return null;
            }

            ContractGenerateTask contractGenerateTask = new ContractGenerateTask();
            contractGenerateTask.setTaskId(applyMiddle.getContractId());
            contractGenerateTask.setApplyId(sonThreeId);
            contractGenerateTask.setHouseId(applyMiddle.getHouseId());
            contractGenerateTask.setLandlordId(applyMiddle.getLandId());
            contractGenerateTask.setTenantId(applyMiddle.getTenantId());
            contractGenerateTask.setFileId(applyMiddle.getFileId());
            if (StrUtil.isBlank(applyMiddle.getFileId())) {
                contractGenerateTask.setStatus(ContractTaskStatusEnum.GENERATING);
            } else {
                contractGenerateTask.setStatus(ContractTaskStatusEnum.COMPLETED);
            }
            // 获取任务状态
            return contractGenerateTask;
        } catch (Exception e) {
            log.warn("获取异步合同任务状态失败, sonThreeId: {}, error: {}", sonThreeId, e.getMessage());
            return null;
        }
    }

    public String getThreeReject(String threeId) {
        LambdaQueryWrapper<XApplyMiddle> xApplyMiddleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        xApplyMiddleLambdaQueryWrapper.eq(XApplyMiddle::getSonThreeId, threeId);
        XApplyMiddle one = xApplyMiddleService.getOne(xApplyMiddleLambdaQueryWrapper);
        return one.getSonThreeReason();
    }
}
